﻿using Flurl.Http;
using Newtonsoft.Json.Linq;

namespace BarrageGameAssistant.Core.Utils
{
    public class IpAddressInfo
    {
        public string IpAddress { get; set; }

        public string Area { get; set; }

        public IpAddressInfo(string ipAddress, string area)
        {
            IpAddress = ipAddress;
            Area = area;
        }

        public override string ToString()
        {
            return $"{IpAddress}|{Area}";
        }
    }

    public class NetUtils
    {
        public static IpAddressInfo? GetIp()
        {
            try
            {
                System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
                string url = "http://whois.pconline.com.cn/ipJson.jsp";
                string content = url.WithHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36")
                    .WithHeader("Accept", "application/json, text/plain, */*")
                    .WithHeader("Accept-Encoding", "gzip, deflate, br")
                    .WithHeader("Accept-Language", "zh-CN,zh-TW;q=0.9,zh;q=0.8,en;q=0.7,en-GB;q=0.6,en-US;q=0.5")
                    .WithHeader("Cache-Control", "no-cache")
                    .WithHeader("Content-Type", "application/x-www-form-urlencoded")
                    .WithHeader("Origin", "http://whois.pconline.com.cn")
                    .WithHeader("Referer", "http://whois.pconline.com.cn/")
                    .GetStringAsync().GetAwaiter().GetResult();
                content = content.Replace("if(window.IPCallBack) {IPCallBack(", "");
                content = content.Replace(");}", "");
                var obj = JObject.Parse(content);

                var ip = obj?["ip"]?.ToString();
                var addr = obj?["addr"]?.ToString();
                if (!string.IsNullOrEmpty(addr))
                    addr = addr.Replace(" ", "");

#pragma warning disable CS8604 // 引用类型参数可能为 null。
                return new IpAddressInfo(ip, addr);
#pragma warning restore CS8604 // 引用类型参数可能为 null。
            }
            catch (Exception)
            {
                return null;
            }
        }
    }
}
